// © 2009 Microsoft Corporation.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.UserControls;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.TasksService;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.NotificationsService;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.AuthZService;
using Microsoft.Security.Application;
using Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Common;

namespace Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Tasks
{
    public partial class viewtask : System.Web.UI.Page
    {
        List<TaskStatus> lstStatus = null;
        List<Group> lstGroups = null;
        List<Category> lstCategories = null;
        List<Microsoft.InformationSecurity.CISF.Security.AuthZServices.User> lstUsers = null;
        List<Microsoft.InformationSecurity.RiskManagement.ISRMWeb.NotificationsService.NotificationSchedule> lstSchedules = null;
        int taskID = 0;
        Task task = null;

        bool blnReadOnly = true;

        public void Page_Error(object sender, EventArgs e)
        {
            if (Server.GetLastError() is HttpException)
            {
                throw new HttpException(((HttpException)Server.GetLastError()).GetHttpCode(), Server.GetLastError().Message);
            }
            else
                throw new HttpException(500, "Unhandled Exception.");
        }


        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskUser")))
                throw new HttpException(403, "Requires Task User role");
            else
            {
                blnReadOnly = false;
            }

            if (Request.QueryString["taskid"] != "")
            {
                int.TryParse(Request.QueryString["taskid"], out taskID);
                if (taskID < 1)
                {
                    Response.Redirect("ViewTasks.aspx");
                }
            }

            TasksServiceClient tasks = new TasksServiceClient();
            if (ViewState["Status"] == null)
            {
                lstStatus = new List<TaskStatus>();
                lstStatus.AddRange(tasks.GetAllTaskStatus());
                lstGroups = new List<Group>();
                lstGroups.AddRange(tasks.GetActiveGroups());
                lstCategories = new List<Category>();
                lstCategories.AddRange(tasks.GetActiveCategories());
                lstUsers = new List<Microsoft.InformationSecurity.CISF.Security.AuthZServices.User>();
                if (this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager")))
                {
                    AuthZServiceClient objClient = new AuthZServiceClient();
                    lstUsers.AddRange(objClient.GetUsersInRole("Task User"));
                    objClient.Close();
                }
                else
                {
                    Microsoft.InformationSecurity.CISF.Security.AuthZServices.User usr = new Microsoft.InformationSecurity.CISF.Security.AuthZServices.User();
                    usr.PersonId = ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId;
                    usr.FullName = ((CISF.Security.Principal.CISFIdentity)User.Identity).FullName;
                    lstUsers.Add(usr);
                }
                lstUsers.Sort(new UserComparer());
                lstSchedules = new List<Microsoft.InformationSecurity.RiskManagement.ISRMWeb.NotificationsService.NotificationSchedule>();
                NotificationsServiceClient notClient = new NotificationsServiceClient();
                lstSchedules.AddRange(notClient.GetNotificationSchedules());
                notClient.Close();
                this.DoDataBind();
                ViewState["Status"] = lstStatus;
                ViewState["Groups"] = lstGroups;
                ViewState["Categories"] = lstCategories;
                ViewState["Users"] = lstUsers;
                ViewState["NotificationSchedules"] = lstSchedules;
            }
            else
            {
                lstStatus = (List<TaskStatus>)ViewState["Status"];
                lstGroups = (List<Group>)ViewState["Groups"];
                lstCategories = (List<Category>)ViewState["Categories"];
                lstUsers = (List<Microsoft.InformationSecurity.CISF.Security.AuthZServices.User>)ViewState["Users"];
                lstSchedules = (List<Microsoft.InformationSecurity.RiskManagement.ISRMWeb.NotificationsService.NotificationSchedule>)ViewState["Schedules"];
            }

            if (!Page.IsPostBack)
            {
                lblPageHeader.Text = "View Task Details";
                task = tasks.GetTask(taskID);
                if (task != null)
                {
                    if (!this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager")))
                    {
                        if (((CISF.Security.Principal.CISFIdentity)this.User.Identity).PersonId != task.AssignedTo.ID)
                        {
                            blnReadOnly = true;
                        }

                        if (User.IsInRole(Utility.GetConfigurationValue("TrustedTaskUser")))
                        {
                            bool isValidTTU = tasks.IsValidTrustedTaskUser(taskID, ((CISF.Security.Principal.CISFIdentity)this.User.Identity).PersonId);
                            if (!isValidTTU)
                                throw new HttpException(403, "Requires Task Manager role");

                        }

                        if ((((CISF.Security.Principal.CISFIdentity)this.User.Identity).PersonId != task.AssignedTo.ID) && !User.IsInRole(Utility.GetConfigurationValue("TrustedTaskUser")))
                        {
                            throw new HttpException(403, "Requires Task Manager role");
                        }
                    }

                    if (!blnReadOnly)
                    {
                        txtTitle.Visible = true;
                        txtDescription.Visible = true;
                        validationSummary.Enabled = true;
                        titleRequired.Enabled = true;
                        ddlCategory.Visible = true;
                        categoryRequired.Enabled = true;
                        groupRequired.Enabled = true;
                        ddlGroup.Visible = true;
                        ddlNotification.Visible = true;
                        ddlStatus.Visible = true;
                        txtHoursSpent.Visible = true;
                        btnSave.Visible = true;
                        btnCancel.Visible = true;
                        if (!this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager")))
                        {
                            lblOwner.Visible = true;
                            lblDueDate.Visible = true;
                        }
                        else
                        {
                            ddlOwner.Visible = true;
                            txtDueDate.Visible = true;
                            imgDueDateCalendar.Visible = true;
                        }

                        txtTitle.Text = task.Name;
                        txtDescription.Text = task.Description;
                        dueDateCalendar.SelectedDate = task.DueDate;
                        txtHoursSpent.Text = task.HoursSpent.ToString();
                        ListItem li = ddlCategory.Items.FindByValue(task.Category.ID.ToString());
                        if (li != null)
                            li.Selected = true;

                        li = ddlGroup.Items.FindByValue(task.Group.ID.ToString());
                        if (li != null)
                            li.Selected = true;

                        li = ddlNotification.Items.FindByValue(task.NotificationSchedule.ID.ToString());
                        if (li != null)
                            li.Selected = true;

                        if (!this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager")))
                        {
                            lblDueDate.Text = AntiXss.HtmlEncode(task.DueDate.ToString("MM/dd/yyyy"));
                            lblOwner.Text = AntiXss.HtmlEncode(task.AssignedTo.Name);
                        }
                        else
                        {
                            txtDueDate.Text = task.DueDate.ToString("MM/dd/yyyy");
                            ddlOwner.Items.FindByValue(task.AssignedTo.ID.ToString()).Selected = true;
                        }

                        li = ddlStatus.Items.FindByValue(task.Status.ID.ToString());
                        if (li != null)
                            li.Selected = true;
                    }
                    else
                    {
                        lblTitle.Visible = true;
                        lblDescription.Visible = true;
                        lblDueDate.Visible = true;
                        lblCategory.Visible = true;
                        lblGroup.Visible = true;
                        lblNotification.Visible = true;
                        lblOwner.Visible = true;
                        lblStatus.Visible = true;
                        lblHoursSpent.Visible = true;

                        lblTitle.Text = AntiXss.HtmlEncode(task.Name);
                        lblDescription.Text = AntiXss.HtmlEncode(task.Description).Replace("&#13;&#10;", "<br />");
                        lblDueDate.Text = AntiXss.HtmlEncode(task.DueDate.ToString("MM/dd/yyyy"));
                        lblHoursSpent.Text = AntiXss.HtmlEncode(task.HoursSpent.ToString());
                        lblCategory.Text = AntiXss.HtmlEncode(task.Category.Name);
                        lblGroup.Text = AntiXss.HtmlEncode(task.Group.Name);
                        lblNotification.Text = AntiXss.HtmlEncode(task.NotificationSchedule.Name);
                        lblOwner.Text = AntiXss.HtmlEncode(task.AssignedTo.Name);
                        lblStatus.Text = AntiXss.HtmlEncode(task.Status.Name);
                    }
                    if (this.Context.User.IsInRole(Utility.GetConfigurationValue("TrustedTaskUser")))
                    {
                        hlRisk.NavigateUrl = "../Risks/SubmitRisk.aspx?RiskID=" + task.BusinessObject.ID.ToString();
                        hlRisk.Text = AntiXss.HtmlEncode(task.BusinessObject.Name);
                    }
                    ViewState["Task"] = task;
                }
                else
                {
                    Response.Redirect("ViewTasks.aspx");
                }
            }
            else
                if (ViewState["Task"] != null && ViewState["Task"] is Task)
                    task = (Task)ViewState["Task"];

            tasks.Close();
        }

        private void DoDataBind()
        {
            if (lstStatus != null)
            {
                ddlStatus.DataTextField = "Name";
                ddlStatus.DataValueField = "ID";
                ddlStatus.DataSource = lstStatus;
                ddlStatus.DataBind();
            }
            if (lstGroups != null)
            {
                ddlGroup.DataTextField = "Name";
                ddlGroup.DataValueField = "ID";
                ddlGroup.DataSource = lstGroups;
                ddlGroup.DataBind();
                ddlGroup.Items.Insert(0, new ListItem("", ""));
            }
            if (lstCategories != null)
            {
                ddlCategory.DataTextField = "Name";
                ddlCategory.DataValueField = "ID";
                ddlCategory.DataSource = lstCategories;
                ddlCategory.DataBind();
                ddlCategory.Items.Insert(0, new ListItem("", ""));
            }
            if (lstUsers != null)
            {
                ddlOwner.DataTextField = "FullName";
                ddlOwner.DataValueField = "PersonId";
                ddlOwner.DataSource = lstUsers;
                ddlOwner.DataBind();
            }
            if (lstSchedules != null)
            {
                ddlNotification.DataTextField = "Name";
                ddlNotification.DataValueField = "ID";
                ddlNotification.DataSource = lstSchedules;
                ddlNotification.DataBind();
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("ViewTasks.aspx", true);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            int iHoursSpent = 0;
            int.TryParse(txtHoursSpent.Text, out iHoursSpent);
            if (!(this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager")))
                && !(this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskUser")) && ((CISF.Security.Principal.CISFIdentity)this.User.Identity).PersonId == task.AssignedTo.ID))
            {
                Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASK_NO_PERM"), "Error", true);
            }

            if (iHoursSpent < 0)
            {
                Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASK_HOURS_NOTVALID"), "Error", true);
                txtHoursSpent.Text = "0";
                return;
            }
            if (iHoursSpent > 65536)
            {
                Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASK_HOURS_NOTVALID2"), "Error", true);
                txtHoursSpent.Text = "0";
                return;
            }

            try
            {
                if (this.Context.User.IsInRole(Utility.GetConfigurationValue("TaskManager")))
                {
                    DateTime dtNewDueDate;
                    DateTime.TryParse(txtDueDate.Text, out dtNewDueDate);
                    DateTime currentDate = DateTime.Parse(DateTime.Now.ToString("MM/dd/yyyy"));
                    if (dtNewDueDate.Subtract(currentDate).Days < 0)
                    {
                        Utility.ShowMessage(this.Page.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASK_DUEDATE_NOTVALID"), "Error", true);
                        txtDueDate.Text = currentDate.ToString("MM/dd/yyyy");
                        return;
                    }
                    task.AssignedTo.ID = int.Parse(ddlOwner.SelectedValue);
                    task.DueDate = DateTime.Parse(txtDueDate.Text);
                }
                task.Name = txtTitle.Text;
                task.Description = txtDescription.Text;
                task.Category.ID = int.Parse(ddlCategory.SelectedValue);
                task.Group.ID = int.Parse(ddlGroup.SelectedValue);
                task.HoursSpent = iHoursSpent;
                task.LastUpdatedBy = Utility.GetUserFullName();
                task.NotificationSchedule.ID = int.Parse(ddlNotification.SelectedValue);
                task.Status.ID = int.Parse(ddlStatus.SelectedValue);
                task.PersonID = ((CISF.Security.Principal.CISFIdentity)User.Identity).PersonId;
                TasksServiceClient taskClient = new TasksServiceClient();
                taskClient.UpdateTask(task);
                taskClient.Close();
                Response.Redirect("ViewTasks.aspx");
            }
            catch (System.ServiceModel.FaultException<System.ServiceModel.ExceptionDetail> fex)
            {
                if (fex.Detail.Type == typeof(ArgumentException).ToString() || fex.Detail.Type == typeof(ArgumentNullException).ToString())
                {
                    Utility.ShowMessage(this.Master, fex.Message.ToString(), "Error", true);
                }
                else
                    Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASK_SAVE_UNKWNERR"), "Error", true);
            }
            catch
            {
                Utility.ShowMessage(this.Master, Utility.GetResourceString("Microsoft.InformationSecurity.RiskManagement.ISRMWeb.Resources.TaskMessages", "TASK_SAVE_UNKWNERR"), "Error", true);
            }
        }
    }

    internal class UserComparer : IComparer<Microsoft.InformationSecurity.CISF.Security.AuthZServices.User>
    {

        #region IComparer<User> Members

        public int Compare(Microsoft.InformationSecurity.CISF.Security.AuthZServices.User x, Microsoft.InformationSecurity.CISF.Security.AuthZServices.User y)
        {
            return StringComparer.CurrentCulture.Compare(x.FullName, y.FullName);
        }

        #endregion
    }
}
